use std::fs::File;
use std::io::Write;

use super::check::SystemInfoAndBuild;
use super::routes::Parameter;
// use net_brd::Chain;
use serde_json::json;
use net_brd::LocInfo;
use net_brd::net;
use net_brd::ChainData;
use net_brd::Chain;
use net_brd::ls_brd;
use net_brd::Client;
use net_brd::data::ChainNet;
use net_brd::Color;

use super::broadcast::onlines;
use super::config::get_config_password;
lazy_static!{
    static ref WHO_AM_I:String =  {
        net::who_am_i()
    };
}


pub fn alive_protocol(_: &Parameter, _: &SystemInfoAndBuild) -> (i32, String) {
    let mut l = LocInfo::default();
    l.uids = ls_brd();
    l.host = WHO_AM_I.clone();
    let res = json!(l).to_string();
    log::info!("{}", &res);
    (1, res)
}

#[allow(unreachable_code)]
pub fn action_protocol(para: &Parameter, _: &SystemInfoAndBuild) -> (i32, String) {
    let content = para.data.clone();
    let c = Client::new(&get_config_password());
    let default_option = (1, Chain::default().to_json());
    log::info!("{}", content.yellow());
    if para.op == "nodes"{
        return (0, json!(onlines()).to_string());
    }else if para.op == "circle"{
        let uids:Vec<&str> = para.data_tp.split(".").collect();
        if let Some(chain) = uids[0].chain_load(){
            let output_task = format!("{}.{}",chain.loc.path,uids[1]);
            if let Ok(mut f) = File::create(output_task){
                log::info!("circle : {}.{} | len: {}", uids[0] ,uids[1], para.data.len());
                let _ = f.write_all(para.data.as_bytes());
            }
        }

    }else{
        if let Some(chain) = content.chain_load_json(){
            match chain.action.as_str() {
                "run" => {
                    c.action(&chain);
                    log::info!("{}", &chain);
                    return (0, chain.to_json());
                },
                "get" => {
                    if let Some(chain) = chain.loc.uid.chain_load(){
                        return (0, chain.to_json());
                    }else{
                        return default_option;
                    }
                },
                "pass" => {
                    if let Some(mut chain) = chain.loc.uid.chain_load(){
                        if chain.sub_chains.len() > 1{
                            chain.sub_chains[0].pass(&c.clone());
                            return default_option;
                        }else{
                            return (0, chain.to_json());
                        }
                    }else{
                        return default_option;
                    }
                }
                _ => {
                    return default_option;
                }
            }
        }else{
            return default_option;
        }
    }
    default_option
}
